package com.cz.nongyetongv5.activity;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.cz.nongyetongv5.R;
import com.cz.nongyetongv5.adapter.RecordHistoryAdapter;
import com.cz.nongyetongv5.application.InitApplication;
import com.cz.nongyetongv5.bean.RecordHistory;
import com.cz.nongyetongv5.bean.User;
import com.cz.nongyetongv5.utils.CharsetUtil;
import com.cz.nongyetongv5.utils.ConfigUtil;
import com.cz.nongyetongv5.utils.GoHomeUtil;
import com.cz.nongyetongv5.utils.HttpUtils;
import com.cz.nongyetongv5.utils.HttpUtils.OnRequestExecuted;

public class RecordHistoryActivity extends Activity {

	private ListView lvList = null;

	private RecordHistoryAdapter adpAdapter;
	/**
	 * ListView 底部的一些属性
	 */
	private View bottomView = null;

	private ProgressBar bottomProgress = null;

	private TextView bottomTextView = null;

	private List data;

	private final int PAGE_SIZE = 20;

	private int PAGE_INDEX = 0;

	private int PAGE_COUNT = 0;

	private String url;

	private User user;

	private ConfigUtil configUtil = null;

	private TextView titleState = null;

	@Override
	protected void onDestroy() {

		InitApplication initApplication = (InitApplication) getApplicationContext();

		initApplication.getActivities().remove(this);

		// TODO Auto-generated method stub
		super.onDestroy();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		configUtil = new ConfigUtil(getResources());
		InitApplication initApplication = (InitApplication) getApplicationContext();

		initApplication.getActivities().add(this);

		setContentView(R.layout.record_history);

		titleState = (TextView) findViewById(R.id.titleState);

		titleState.setText("当前数据:今年");

		user = (User) getIntent().getSerializableExtra("user");

		ViewGroup btnBack = (ViewGroup) findViewById(R.id.btnBack);

		btnBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				onBackPressed();

			}
		});

		data = (List) getIntent().getSerializableExtra("data");

		if (data == null) {

			data = new ArrayList();

		}

		String title = getIntent().getStringExtra("title");

		url = getIntent().getStringExtra("url");

		/**
		 * 公用页面区别是否显示底部
		 */
		boolean isMore = getIntent().getBooleanExtra("more", false);

		TextView tvTitle = (TextView) findViewById(R.id.tvTitle);

		tvTitle.setText(title);

		lvList = (ListView) findViewById(R.id.lvList);

		lvList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
									int position, long arg3) {

				Object obj = adpAdapter.getItem(position);

				String id = ((RecordHistory) obj).getId();

				Intent intent = new Intent(RecordHistoryActivity.this,
						RecordHistoryDetailActivity.class);

				intent.putExtra("user", user);

				if (url.indexOf("check") > -1) {

					String url = configUtil.getPreHttpUrl()
							+ getResources()
							.getString(
									R.string.recordhistory_detail_jiandujiancha)
							+ id + "/from/1/username/" + user.getUsername();

					intent.putExtra("url", url);

				}

				// 产品检测
				if (url.indexOf("monitor") > -1) {

					String url = configUtil.getPreHttpUrl()
							+ getResources()
							.getString(
									R.string.recordhistory_detail_chanpinjiance)
							+ id + "/from/1/username/" + user.getUsername();

					intent.putExtra("url", url);
				}

				// 督查巡查
				if (url.indexOf("inspect") > -1) {
					String url = configUtil.getPreHttpUrl()
							+ getResources().getString(
							R.string.recordhistory_detail_duchaxuncha)
							+ id + "/from/1/username/" + user.getUsername();

					intent.putExtra("url", url);

				}

				startActivity(intent);

			}
		});

		lvList.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {

				switch (scrollState) {
					case OnScrollListener.SCROLL_STATE_FLING:

						adpAdapter.setFlagBusy(true);
						break;
					case OnScrollListener.SCROLL_STATE_IDLE:
						adpAdapter.setFlagBusy(false);
						break;
					case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
						adpAdapter.setFlagBusy(false);
						break;
					default:
						break;
				}

				adpAdapter.notifyDataSetChanged();

			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
								 int visibleItemCount, int totalItemCount) {

			}
		});

		adpAdapter = new RecordHistoryAdapter(this, data);

		// 确定显示底部信息的时候才进行添加底部信息

		if (isMore) {

			bottomView = LayoutInflater.from(this).inflate(
					R.layout.listfooter_more, null);
			bottomView.setVisibility(View.VISIBLE);

			bottomProgress = (ProgressBar) bottomView
					.findViewById(R.id.pull_to_refresh_progress);
			bottomProgress.setVisibility(View.GONE);

			bottomTextView = (TextView) bottomView.findViewById(R.id.load_more);
			bottomTextView.setText("点击加载更多..");

			bottomView.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					doPage();
				}
			});

			lvList.addFooterView(bottomView, null, false);

			lvList.setAdapter(adpAdapter);

			doPage();

		} else {
			// lvList.setAdapter(adpAdapter);
		}

		loadRightTitle();

	}

	/**
	 * 加载去主页的按钮
	 */
	public void loadRightTitle() {

		ViewGroup btnMeanMore = (ViewGroup) findViewById(R.id.btnMeanMore);

		View view = GoHomeUtil.createPopView(getApplicationContext(),
				new String[] { "主页", "去年", "今年" });

		// 弹出更多的菜单
		final PopupWindow pop = new PopupWindow(view,
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, false);

		// 需要设置一下此参数，点击外边可消失
		pop.setBackgroundDrawable(new BitmapDrawable());

		// 设置点击窗口外边窗口消失
		pop.setOutsideTouchable(true);

		// 设置此参数获得焦点，否则无法点击
		pop.setFocusable(true);

		final Button btn01 = (Button) pop.getContentView().findViewWithTag(
				"btn0");

		final Button btn02 = (Button) pop.getContentView().findViewWithTag(
				"btn1");

		final Button btn03 = (Button) pop.getContentView().findViewWithTag(
				"btn2");

		OnClickListener menuOnClick = new OnClickListener() {

			@Override
			public void onClick(View v) {

				if (v == btn01) {
					GoHomeUtil.goHome(getApplicationContext());
				}

				if (v == btn02) {

					PAGE_INDEX = 0;

					PAGE_COUNT = 0;

					if (data != null) {
						data.clear();
					}

					GregorianCalendar calendar = new GregorianCalendar();
					calendar.add(Calendar.YEAR, -1);

					String year = calendar.get(Calendar.YEAR) + "";

					url = getIntent().getStringExtra("url");

					url = url.replaceAll("this_year/1/", "");

					url = url + "/year/" + year;

					Log.d("url~~", url);

					doPage();

					titleState.setText("当前数据:去年");

				}

				if (v == btn03) {

					PAGE_INDEX = 0;

					PAGE_COUNT = 0;

					if (data != null) {
						data.clear();
					}

					url = getIntent().getStringExtra("url");

					Log.d("url~~", url);

					doPage();

					titleState.setText("当前数据:今年");
				}

				pop.dismiss();
			}
		};

		btn01.setOnClickListener(menuOnClick);

		btn02.setOnClickListener(menuOnClick);
		btn03.setOnClickListener(menuOnClick);

		btnMeanMore = (ViewGroup) findViewById(R.id.btnMeanMore);

		btnMeanMore.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				if (pop.isShowing()) {
					// 隐藏窗口，如果设置了点击窗口外小时即不需要此方式隐藏
					pop.dismiss();
				} else {
					// 显示窗口
					pop.showAsDropDown(v);
				}

			}
		});

	}

	public void doPage() {

		new AsyncTask<Integer, Integer, Integer>() {

			private int responseCodeRet;

			private String responseBodyRet;

			@Override
			protected Integer doInBackground(Integer... params) {

				String authUserName = new ConfigUtil(getResources())
						.getRestUsername();

				String authPassword = new ConfigUtil(getResources())
						.getRestPassword();

				authUserName = configUtil.getRestUsername();
				authPassword = configUtil.getRestPassword();

				String requestUrl = url.replaceAll("@offset",
						(PAGE_INDEX * PAGE_SIZE) + "").replaceAll("@limit",
						PAGE_SIZE + "");

				HttpUtils httpUtils = HttpUtils.getInstance();

				httpUtils.setOnRequestExecuted(new OnRequestExecuted() {

					@Override
					public void onRequestExecuted(int responseCode,
												  String responseBody) {

						responseCodeRet = responseCode;

						responseBodyRet = responseBody;

					}
				});

				httpUtils.sendRequest(requestUrl, null, "GET", "UTF-8",
						authUserName, authPassword, user);

				Log.d("url~~", requestUrl);
				return null;
			}

			@Override
			protected void onPostExecute(Integer result) {

				try {
					JSONObject jsonObject = new JSONObject(responseBodyRet);

					String status = jsonObject.getString("status");

					if ("true".equals(status) || "1".equals(status)) {

						int totalCount = jsonObject.getInt("total");

						PAGE_COUNT = totalCount % PAGE_SIZE == 0 ? totalCount
								/ PAGE_SIZE : (totalCount / PAGE_SIZE) + 1;

						if (PAGE_INDEX >= PAGE_COUNT) {
							Toast.makeText(RecordHistoryActivity.this,
									"没有更多数据了...", Toast.LENGTH_SHORT).show();

							bottomView.setVisibility(View.GONE);

							this.cancel(true);

							return;

						}

						JSONArray jsonArray = jsonObject.getJSONArray("result");

						for (int i = 0; i < jsonArray.length(); i++) {

							JSONObject itemJson = jsonArray.getJSONObject(i);

							RecordHistory history = null;

							if (url.indexOf("check") > -1) {

								// 监督检查
								String id = itemJson.getString("id");

								String date = itemJson.getString("date");

								String enterprise_names = "";

								if (!itemJson.isNull("enterprises")) {

									JSONArray enterpriseNames = itemJson
											.getJSONArray("enterprises");

									for (int j = 0; j < enterpriseNames
											.length(); j++) {

										String item = enterpriseNames
												.getString(j);

										enterprise_names += item + ";";

									}

								}

								if (enterprise_names.endsWith(";")) {
									enterprise_names = enterprise_names
											.substring(
													0,
													enterprise_names.length() - 1);
								}

								String department_names = "";

								if (!itemJson.isNull("departments")) {

									JSONArray departmentNames = itemJson
											.getJSONArray("departments");

									for (int j = 0; j < departmentNames
											.length(); j++) {

										String item = departmentNames
												.getString(j);

										department_names += item + ";";

									}

								}

								if (department_names.endsWith(";")) {
									department_names = department_names
											.substring(
													0,
													department_names.length() - 1);
								}

								String inspector_names = "";

								if (!itemJson.isNull("inspectors")) {

									JSONArray inspectorNames = itemJson
											.getJSONArray("inspectors");

									for (int j = 0; j < inspectorNames.length(); j++) {

										String item = inspectorNames
												.getString(j);

										inspector_names += item + ";";

									}

								}

								if (inspector_names.endsWith(";")) {
									inspector_names = inspector_names
											.substring(
													0,
													inspector_names.length() - 1);
								}

								int result_final = itemJson.getJSONObject(
										"result").getInt("final");

								String photo = itemJson.getString("photo");

								history = new RecordHistory();

								history.setBeiJianName(enterprise_names);

								history.setJianGuanName(department_names);

								history.setRenYuan(inspector_names);

								history.setChanPin(null);

								history.setResult(result_final);

								history.setTime(date);

								history.setId(id);

								history.setImageUrl(photo);

							} else if (url.indexOf("monitor") > -1) {
								// 产品检测

								String id = itemJson.getString("id");

								String date = itemJson.getString("date");

								String enterprise_names = (String) itemJson
										.getJSONObject("enterprise").getString(
												"name");

								String detector_name = itemJson.getJSONObject(
										"detector").getString("name");

								String worker_names = "";

								JSONArray workName = itemJson
										.getJSONArray("workers");

								for (int j = 0; j < workName.length(); j++) {

									String item = workName.getString(j);

									worker_names += item + ";";

								}

								if (worker_names.endsWith(";")) {

									worker_names = worker_names.substring(0,
											worker_names.length() - 1);
								}

								String record_names = "";

								JSONArray recordName = itemJson.getJSONObject(
										"record").getJSONArray("names");

								for (int j = 0; j < recordName.length(); j++) {

									String item = recordName.getString(j);

									record_names += item + ";";

								}

								if (record_names.endsWith(";")) {

									record_names = record_names.substring(0,
											record_names.length() - 1);
								}

								int record_count_unqualified = itemJson
										.getJSONObject("record")
										.getJSONArray("unqualified").length();

								//
								String requestUrl = new ConfigUtil(
										getResources()).getPreHttpUrl()
										+ getString(R.string.chanpinjiance_history_url);

								// if (RecordHistoryActivity.this.url
								// .startsWith(requestUrl)) {
								//
								// if (record_count_unqualified == 0) {
								// record_count_unqualified = 1;
								//
								// } else {
								//
								// record_count_unqualified = 0;
								// }
								//
								// }

								String photo = itemJson.getString("photo");

								history = new RecordHistory();

								history.setBeiJianName(enterprise_names);

								history.setJianGuanName(detector_name);

								history.setRenYuan(worker_names);

								history.setChanPin(record_names);

								history.setResult(record_count_unqualified);

								history.setTime(date);

								history.setId(id);

								history.setImageUrl(photo);

							} else if (url.indexOf("inspect") > -1) {

								// 督查巡查
								String id = itemJson.getString("id");

								String date = itemJson.getString("date");

								String enterprise_names = "";

								if (!itemJson.isNull("enterprises")) {

									JSONArray enterpriseNames = itemJson
											.getJSONArray("enterprises");

									for (int j = 0; j < enterpriseNames
											.length(); j++) {

										String item = enterpriseNames
												.getString(j);

										enterprise_names += item + ";";

									}

								}

								if (enterprise_names.endsWith(";")) {
									enterprise_names = enterprise_names
											.substring(
													0,
													enterprise_names.length() - 1);
								}

								String department_names = "";

								if (!itemJson.isNull("departments")) {

									JSONArray departmentNames = itemJson
											.getJSONArray("departments");

									for (int j = 0; j < departmentNames
											.length(); j++) {

										String item = departmentNames
												.getString(j);

										department_names += item + ";";

									}

								}

								if (department_names.endsWith(";")) {
									department_names = department_names
											.substring(
													0,
													department_names.length() - 1);
								}

								String inspector_names = "";

								if (!itemJson.isNull("inspectors")) {

									JSONArray inspectorNames = itemJson
											.getJSONArray("inspectors");

									for (int j = 0; j < inspectorNames.length(); j++) {

										String item = inspectorNames
												.getString(j);

										inspector_names += item + ";";

									}

								}

								if (inspector_names.endsWith(";")) {
									inspector_names = inspector_names
											.substring(
													0,
													inspector_names.length() - 1);
								}

								int result_final = itemJson.getJSONObject(
										"result").getInt("final");

								String photo = itemJson.getString("photo");

								history = new RecordHistory();

								history.setBeiJianName(enterprise_names);

								history.setJianGuanName(department_names);

								history.setRenYuan(inspector_names);

								history.setChanPin(null);

								history.setResult(result_final);

								history.setTime(date);

								history.setId(id);

								history.setImageUrl(photo);

							}

							if (history != null) {

								if (url.indexOf("inspect") > -1) {

									if (history.getResult() > 0
											&& CharsetUtil.isNotNull(history
											.getBeiJianName())) {

										data.add(history);

									}

								} else {

									data.add(history);
								}

							}

						}

						adpAdapter.notifyDataSetChanged();

					} else {
						Toast.makeText(RecordHistoryActivity.this,
								"没有加载到相关数据...", Toast.LENGTH_SHORT).show();

					}

				} catch (JSONException e) {
					e.printStackTrace();
				}

				adpAdapter.notifyDataSetChanged();

				PAGE_INDEX++;

				bottomProgress.setVisibility(View.GONE);
				bottomTextView.setText("点击加载更多..");

				super.onPostExecute(result);
			}

			@Override
			protected void onPreExecute() {

				bottomProgress.setVisibility(View.VISIBLE);
				bottomTextView.setText("正在加载..");

				super.onPreExecute();
			}

		}.execute();

	}
}
